<?php
// +----------------------------------------------------------------------
// | Author: July
// +----------------------------------------------------------------------
// | 创建时间: 2023-12-27 20:39:42
// +----------------------------------------------------------------------
// | 缓存控制器
// +----------------------------------------------------------------------

namespace july\julyadmin\admin\controller;

use july\julyadmin\builder\traits\HasBuilder;

class Cache extends Common
{
    use HasBuilder;

    //不需要登录验证的控制器和方法，如：['index']
    protected $noNeedLogin = [];
    //不需要权限验证的控制器和方法，如：['index']
    protected $noPermissionAuth = ['*'];

    public function __construct()
    {
        //重新初始化父类
        parent::initialize();

    }

    /**
     * 清除缓存
     */
    public function clearCache()
    {

        if (request()->isPost()) {
            $data = request()->only([
                'cache_key',
            ], 'post');

            if (in_array('route', $data['cache_key'])) {
                \think\facade\Route::clear();
            }
            if (in_array('cache', $data['cache_key'])) {
                \think\facade\Cache::clear();
            }
            if (in_array('template', $data['cache_key'])) {
                $this->deleteCache(app()->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . 'temp');
                $this->deleteCache(app()->getRuntimePath() . 'temp');
            }
            $this->success('操作成功');
        } else {
            $builder = $this->builder();
            $form    = new \july\julyadmin\builder\Form($builder, '清除缓存');
            $form->setColWidth(12);
            $options = [
                'route'    => '路由缓存',
                'template' => '模板缓存',
                'cache'    => '数据缓存',
            ];
            $form->show('checkbox', 'cache_key', '缓存')->options($options)->required();
            $form->render();
        }
    }

    /**
     * 递归删除缓存文件
     * @Author
     * @DateTime 2023-06-30T23:37:40+0800
     * @param    string                   $dir 缓存目录
     */
    public function deleteCache($dir = '')
    {
        if (!is_readable($dir)) {
            return false;
        }
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != '.' && $file != '..') {
                $fullpath = $dir . '/' . $file;
                if (is_dir($fullpath)) {
                    $this->deleteCache($fullpath);
                } else {
                    unlink($fullpath);
                }
            }
        }
        closedir($dh);
    }
}
